package com.example.zkWebClient.web;

import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.zkWebClient.common.AjaxCommonResult;
import com.example.zkWebClient.utils.ZooKeeperClientUtils;

@Controller
public class IndexController {

	private static final Logger LOGGER = LoggerFactory.getLogger(IndexController.class);

	@GetMapping("/")
	public String main() {
		return "zkWebClient";
	}

	@PostMapping("/conf")
	@ResponseBody
	public Object conf(@RequestParam(value = "connectString", defaultValue = "localhost:2181") String connectString,
			@RequestParam(value = "sessionTimeout", defaultValue = "3000") int sessionTimeout) {
		try {
			final CountDownLatch latch = new CountDownLatch(1);
			ZooKeeper zooKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
				@Override
				public void process(WatchedEvent event) {
					if (event.getState() == KeeperState.SyncConnected && event.getType() == EventType.None) {
						latch.countDown();
					} else if(event.getState() == KeeperState.Expired){
						latch.countDown();
					}
				}
			});
			latch.await();
			ZooKeeperClientUtils.setZooKeeper(zooKeeper);
			return AjaxCommonResult.success(Boolean.TRUE);
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
			return AjaxCommonResult.fail();
		}
	}

}
